package com.liqi.web.controller.device;

import com.liqi.common.annotation.Log;
import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.domain.R;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.common.enums.BusinessType;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.StringUtils;
import com.liqi.common.utils.excel.ExcelUtils;
import com.liqi.common.utils.poi.ExcelUtil;
import com.liqi.common.utils.uuid.GenerateCodeUtils;
import com.liqi.device.domain.DvDrive;
import com.liqi.device.domain.DvModule;
import com.liqi.device.service.IDvDriveService;
import com.liqi.device.service.IDvModuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 驱动管理Controller
 *
 * @author Lwy
 * @date 2022-03-15
 */
@Api(tags = "设备管理")
@RestController
@RequestMapping("/device/drive")
public class DvDriveController extends BaseController {
    @Autowired
    private IDvDriveService dvDriveService;

    @Autowired
    private IDvModuleService dvModuleService;

    /**
     * 查询驱动管理列表
     */
    @ApiOperation("查询驱动")

    @PreAuthorize("@ss.hasPermi('device:drive:list')")
    @GetMapping("/list")
    public TableDataInfo list(DvDrive dvDrive) {
        startPage();
        List<DvDrive> list = dvDriveService.selectDvDriveList(dvDrive);
        return getDataTable(list);
    }

    /**
     * 导出驱动管理列表
     */
    @ApiOperation("导出驱动")
    @PreAuthorize("@ss.hasPermi('device:drive:export')")
    @Log(title = "驱动管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvDrive dvDrive) {

        if (dvDrive.getExportBlank() == 1) {
            List<DvDrive> drives = new ArrayList<>();
            dvDrive = new DvDrive();
            drives.add(dvDrive);
            ExcelUtil<DvDrive> util = new ExcelUtil<DvDrive>(DvDrive.class);
            util.exportExcel(response, drives, "模块数据");
        } else {
            List<DvDrive> list = dvDriveService.selectDvDriveList(dvDrive);
            ExcelUtil<DvDrive> util = new ExcelUtil<DvDrive>(DvDrive.class);
            util.exportExcel(response, list, "驱动管理数据");
        }
    }

    /**
     * 获取驱动管理详细信息
     */

    @PreAuthorize("@ss.hasPermi('device:drive:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(dvDriveService.selectDvDriveById(id));
    }

    /**
     * 新增驱动管理
     */
    @ApiOperation("新增驱动")
    @PreAuthorize("@ss.hasPermi('device:drive:add')")
    @Log(title = "驱动管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DvDrive dvDrive) {
        dvDrive.setDriveCode(GenerateCodeUtils.getSequnce());

        dvDrive.setCreateBy(getUsername());
        dvDrive.setCreateTime(DateUtils.getNowDate());
        dvDrive.setUpdateBy(getUsername());
        dvDrive.setUpdateTime(DateUtils.getNowDate());
        dvDrive.setDeptId(getDeptId().toString());
        dvDrive.setCreateUserId(getUserId().toString());
        return toAjax(dvDriveService.insertDvDrive(dvDrive));
    }

    /**
     * 修改驱动管理
     */
    @PreAuthorize("@ss.hasPermi('device:drive:edit')")
    @Log(title = "驱动管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DvDrive dvDrive) {
        dvDrive.setUpdateBy(getUsername());
        dvDrive.setUpdateTime(DateUtils.getNowDate());
        return toAjax(dvDriveService.updateDvDrive(dvDrive));
    }

    /**
     * 删除驱动管理
     */
    @ApiOperation("删除驱动")
    @PreAuthorize("@ss.hasPermi('device:drive:remove')")
    @Log(title = "驱动管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<DvDrive> removeList = new ArrayList<>();
        List<DvModule> unbindModuleList = new ArrayList<>(); //需要接触绑定的模块
        for (Long id : ids) {
            DvDrive dvDrive = dvDriveService.selectDvDriveById(id); // 遍历每一个选择删除的驱动id
            DvModule dvModule = new DvModule();
            dvModule.setDriveCode(dvDrive.getDriveCode()); //驱动id作为驱动的查询参数
            List<DvModule> dvModules = dvModuleService.selectDvModuleList(dvModule); // 获取与驱动id相关的模块集合
            for (DvModule dvmanager : dvModules) { // 遍历所有的模块，并将要删除的驱动名称和驱动编码设置进去
                dvmanager.setDeleteDriveCode(dvDrive.getDriveCode());
                dvmanager.setDeleteDriveName(dvDrive.getDriveName());
                unbindModuleList.add(dvmanager);
            }
            dvDrive.setUpdateBy(getUsername());
            dvDrive.setUpdateTime(DateUtils.getNowDate());
            dvDrive.setStatus(1);
            removeList.add(dvDrive);
        }
        if (unbindModuleList.size() != 0) {
            return AjaxResult.error("驱动管理已与模块绑定,需要将驱动与指定模块进行解绑", unbindModuleList);
        }
        int i = 0;
        for (DvDrive dvDrive : removeList) {
            i = dvDriveService.updateDvDrive(dvDrive);
        }
        return toAjax(i);
    }

    @ApiOperation("导入驱动excel")
    @PostMapping("/import")
    public R importUser(@RequestPart("file") MultipartFile file) throws Exception {

        List<DvDrive> dvDrives = ExcelUtils.readMultipartFile(file, DvDrive.class);
        String message;
        if (dvDrives.size() == 0) {
            return R.ok("传入的非模板文件,请下载模板文件在进行导入");
        }
        message = dvDriveService.importDvdrive(dvDrives);

        if (StringUtils.isBlank(message)) {
            message = "上传成功！";
        }
        return R.ok(message);
    }

    @ApiOperation("设备名称/厂家词典")
    @GetMapping("/dict")
    public AjaxResult dict() {
        List<DvDrive> dict = dvDriveService.dict();
        return AjaxResult.success(dict);
    }

}
